#!coding=utf-8
from django.core.management.base import BaseCommand, CommandError
from weatherdb.models import DayWeather
from pyExcelerator import *
import datetime
import codecs 
import os
import xlrd
import sys

class Command(BaseCommand):
    help = '导出excel'
    def handle(self, *args, **options):
        path = os.path.abspath(os.path.dirname(sys.argv[0]))
        print 'start________'
        dw = DayWeather.objects.filter(date__gte=datetime.datetime.now().date())
        accu = dw.filter(source='accu')
        moji = dw.filter(source='moji')
        yahoo = dw.filter(source='yahoo')

        w = Workbook() #创建一个工作簿  
        ws = w.add_sheet('Sheet1') #创建一个工作表  
        ws.write_merge(0,0,0,7,'accu')
        ws.write_merge(0,0,8,15,'moji')
        ws.write_merge(0,0,16,23,'yahoo')

        first_line = [u'日期',u'天气',u'最低气温',u'最高气温',u'风级',u'降水',u'省',u'市']
        for i in range(0,len(first_line)):
            ws.write(1,i,first_line[i])
            ws.write(1,i+8,first_line[i])
            ws.write(1,i+16,first_line[i])
        
        for num,a in enumerate(accu):
            ws.write(num+2,0,str(a.date))
            ws.write(num+2,1,a.name)
            ws.write(num+2,2,a.low)
            ws.write(num+2,3,a.height)
            ws.write(num+2,4,(a.wind if a.wind else ''))
            ws.write(num+2,5,(a.rain if a.rain else ''))
            ws.write(num+2,6,a.province)
            ws.write(num+2,7,a.city)

        for num,m in enumerate(moji):
            ws.write(num+2,8,str(m.date))
            ws.write(num+2,9,m.name)
            ws.write(num+2,10,m.low)
            ws.write(num+2,11,m.height)
            ws.write(num+2,12,(m.wind if m.wind else ''))
            ws.write(num+2,13,(m.rain if m.rain else ''))
            ws.write(num+2,14,m.province)
            ws.write(num+2,15,m.city)

        for num,y in enumerate(yahoo):
            ws.write(num+2,16,str(y.date))
            ws.write(num+2,17,y.name)
            ws.write(num+2,18,y.low)
            ws.write(num+2,19,y.height)
            ws.write(num+2,20,(y.wind if y.wind else ''))
            ws.write(num+2,21,(y.rain if y.rain else ''))
            ws.write(num+2,22,y.province)
            ws.write(num+2,23,y.city)

        path = path+'/weatherdb/medias/excel/'
        file =  '%s.xls' % (datetime.datetime.now().date())
        save_path = '%s/%s' % (path,file)
        w.save(save_path) #保存   
        print 'finish'